import Message from '@/components/message'
import axios from 'axios'
import useStore from '@/store'
// 创建一个axios实例
export const baseURL = "http://pcapi-xiaotuxian-front-devtest.itheima.net/"

const request = axios.create({
  // 请求基础路径
  baseURL,
  // baseURL: "https://apipc-xiaotuxian-front.itheima.net/",
  // baseURL: 'http://pcapi-xiaotuxian-front.itheima.net/',

  // 解绑地址
  //  http://pcapi-xiaotuxian-front-devtest.itheima.net/login/social/unbind?mobile=13012345756
  timeout: 3000
})

// 添加请求拦截器
request.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    const { user } = useStore()
    const token = user.userInfo.token
    if (token) {
      config.headers!.Authorization = 'Bearer ' + token
    }
    return config
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
request.interceptors.response.use(
  response => {
    return response
  },
  error => {
    // 对响应错误做点什么
    if (!error.response) {
      Message.error('网络异常，请稍后重置')
    } else {
      // console.log(error.response.data.message)
      const { message, code } = error.response.data
      if (message === '三方登录失败' && code === '501') {
        Message.warning('qq未关联,请先关联qq')
      } else {
        Message.error(message)
      }
    }
    return Promise.reject(error)
  }
)

export default request
